/**
 * 通用工具中心
 * @author aker
 * @date 2020/4/7
 */

import * as moment from 'moment'
import * as _ from 'lodash'
import * as fs from 'fs'
import { concat } from 'lodash'
import * as Ini from 'ini'

import { IAppInfo } from '../Interfaces/IApp'
import ChromeCtl from './ChromeCtl'
import NotifyClass from './Notify'

export const customChrome:any = chrome

export default class Utils {
  private static chromeInfo:IAppInfo = null
  // 类提供Init 方法，外部知道Init 需要给外部调用
  public static Init() {
    this.prepareJob()
  }
  public static async prepareJob() {
    const [err, info] = await callAsync<IAppInfo>(ChromeCtl.chromeGetInfo())
    if (err) {
      console.error("[Utils.prepareJob] chromeGetInfo err: ", err)
      NotifyClass.btn(null, "温馨提示", err.message, new Date().toDateString())
      return
    }
    this.chromeInfo = info
  }
  public static getChromeInfo() {
    return this.chromeInfo
  }
  static arrayBuffertoStr(buf) {
    const encodedString = String.fromCharCode.apply(null, new Uint8Array(buf))
    return decodeURIComponent(escape(encodedString))
  }
  static streamToBuffer(stream:fs.ReadStream):Promise<Buffer> {
    return new Promise((resolve, reject) => {
      const buffers = []
      stream
        .on('data', (data) => buffers.push(data))
        .on('end', () => resolve(Buffer.concat(buffers)))
        .on('error', reject)
    })
  }
  static getDataByFile(formData:any) {
    return new Promise((resolve) => {
      formData.pipe(concat((data) => {
        resolve(data)
      }))
    })
  }
  public static delay(ms=1000) {
    ms = Math.abs(ms)
    return new Promise((resolve) => {
      setTimeout(() => resolve(), ms)
    })
  }
  /**
   * 分析ini 文件
   * @param filePath 分析路径
   */
  public static parseIni(filePath:string):{[key:string]: any} {
    const data = fs.readFileSync(filePath, 'utf-8')
    const config = Ini.parse(data)
    return config
  }
}

global._ = _
global.enableLog = (enable:boolean) => {
  global.printlog = enable ? (msg:string, additions:any[]) => { console.info(moment().format("MM-DD HH:mm:ss  ") + msg, additions ? additions : void 0) } : () => void 0
}
global.enableLog(process.env.NODE_ENV === "dev")

type PathLikeStr = string

interface IChromeInfo {
  agentMode: string
  appDataDir: string
  currentExtensionDir: string
  greenMode: boolean
  homeDir: string
  installDir: string
  platform: string
  product: string
  version: string
}

if (process.env.NODE_ENV === "dev") {
  customChrome.Utils = Utils
  customChrome.moment = moment
}
